﻿using aier.dataaccess.model;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.dataaccess.dapper
{
    public class SequenceDal
    {
        public DapperHelper dapperHelper { get; set; }

        /// <summary>
        /// 根据Key获取Sequence的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int QuerySequnenceByKey(string key)
        {
            return dapperHelper.ExecueWithoutTransaction<int>(a=> {
                string sql = $@"select sequenceVal from aier_mobile.dbo.t_sequence where sequenceKey='{key}'";
                SqlBuilder sqlBuilder = new SqlBuilder();
                var sqlTemplate = sqlBuilder.AddTemplate(sql);
                return a.QueryFirst<int>(sqlTemplate.RawSql);
               
            });
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool CreateSequence(string key)
        {
            return dapperHelper.ExecueWithoutTransaction<bool>(a => {
                string sql =$@"insert into aier_mobile.dbo.t_sequence values('{key}',1);";
                SqlBuilder sqlBuilder = new SqlBuilder();
                var sqlTemplate = sqlBuilder.AddTemplate(sql);
                return a.Execute(sqlTemplate.RawSql) > 0 ? true : false;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sequenceKey"></param>
        /// <returns></returns>
        public bool UpdateVal(string sequenceKey) {
            return dapperHelper.ExecueWithoutTransaction<bool>(a => {
                string sql = $@"update aier_mobile.dbo.t_sequence set sequenceVal = sequenceVal+1 where sequenceKey='{sequenceKey}'";
                SqlBuilder sqlbuilder = new SqlBuilder();
                var sqlTemplate = sqlbuilder.AddTemplate(sql);
                return a.Execute(sqlTemplate.RawSql) > 0 ? true : false;
            });
        }

    }
}
